<template>
	<view>
		<view class="search_bar">
			<uni-search-bar cancelButton="none" :radius="100" @input="input"></uni-search-bar>
		</view>
		
		<view class="result_list" v-if="resultlist.length !== 0">
			<view class="result_item" v-for="(item,index) in resultlist" :key="index">
				<text>{{item.goods_name}}</text>
				<uni-icons type="arrowright" size="15"></uni-icons>
			</view>
		</view>
		
		<view class="history" v-else>
			<view class="history_title">
				<text>搜索历史</text>
				<uni-icons type="trash" size="15" @click="clearhistory"></uni-icons>
			</view>
			<view class="history_list">
				<uni-tag :text="item" v-for="(item,index) in histories" :key="index"></uni-tag>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				keyword: '',
				historylist: [],
				resultlist: [],
				timer: null
			};
		},
		
		onLoad() {
			let str = uni.getStorageSync('kw') || '[]'
			this.historylist = JSON.parse(str)
		},
		
		methods: {
			
			input(e) {
				clearTimeout(this.timer)
				
				this.timer = setTimeout(()=> {
					this.keyword = e.value
					this.searchResult()
				}, 500)
			
			},
			
			async searchResult() {
				
				if (this.keyword.length === 0) {
					this.resultlist = []
					return 
				}

				const { data: res } = await uni.$http.get('/api/public/v1/goods/qsearch', { query: this.keyword })
				if (res.meta.status !== 200) return uni.$showMsg()
				this.resultlist = res.message

				this.savehistory()
			},
			
			savehistory() {
				//this.historylist.push(this.keyword)
				
				const set = new Set(this.historylist)
				set.delete(this.keyword)
				set.add(this.keyword)
				this.historylist = Array.from(set)
				
				// 对搜索历史数据，进行持久化的存储
				let historyStr = JSON.stringify(this.historylist)
				uni.setStorageSync('kw', historyStr)
			},
			
			clearhistory() {
				this.historylist = []
				uni.setStorageSync('kw', '[]')
			}
		},
		
		computed: {
			histories() {
				//值反向(最后一个值变成第一个值)
				return [...this.historylist].reverse()
			}
		}
	}
</script>

<style lang="scss">
.search_bar{
	position: sticky;
	margin-top: 0;
	z-index: 999;
	
	background-color: #c00000;
	
	
}

.result_list {
	padding: 0 5px;
	
	.result_item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		border-bottom: 1px solid #efefef;
		padding: 6px 0;
		
		text {
			font-size: 10px;
			white-space: nowrap; //不换行
			overflow: hidden;
			text-overflow: ellipsis;
		}
		
		
		
	}
}

.history {
	padding: 0 5px;

	.history_title {
		display: flex;
		justify-content: space-between;
		height: 40px;
		border-bottom: 1px solid #efefef;
		align-items: center;
		text {
			font-size: 13px;
		}
		
	}
	
	.history_list {
		display: flex;
		flex-wrap: wrap;
		uni-tag {
			margin-top: 5px;
			margin-right: 5px;
		}
	}
	
}

</style>
